package com.association.main.service.impl;

import com.association.main.domain.MailRequest;
import com.association.main.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    private final JavaMailSender javaMailSender;


    private final ThreadPoolTaskExecutor  executor;
    private final String sendMailer;



    public MailServiceImpl(JavaMailSender javaMailSender,
                           @Qualifier("threadPoolTaskExecutor")ThreadPoolTaskExecutor executor,
                           @Value("${spring.mail.username}") String sendMailer) {
        this.javaMailSender = javaMailSender;
        this.executor = executor;
        this.sendMailer = sendMailer;
    }

    @Override
    public boolean sendHtmlMail(MailRequest mailRequest) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //邮件发件人
            helper.setFrom(sendMailer);
            //邮件收件人 1或多个
            helper.setTo(mailRequest.getSendTo().split(","));
            //邮件主题
            helper.setSubject(mailRequest.getSubject());
            //邮件内容
            helper.setText(mailRequest.getText(), true);
            //邮件发送时间
            helper.setSentDate(new Date());

            String filePath = mailRequest.getFilePath();
            if (StringUtils.hasText(filePath)) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                helper.addAttachment(fileName, file);
            }

            executor.execute(() -> {
                try {
                    javaMailSender.send(message);
                } catch (MailException e) {
                    // 在日志中记录错误信息
                    log.error("邮件发送失败: {}", e.getMessage());
                }
            });

            return true;
        } catch (MessagingException  | MailException e) {
            return false;
        }
    }


}
